package cn.gotom.core.dao.jpa;

import java.util.ResourceBundle;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.apache.log4j.Logger;

public class JpaUtil
{
	private final static Logger log = Logger.getLogger(JpaUtil.class);
	private static final ThreadLocal<EntityManager> entityManagerPool = new ThreadLocal<EntityManager>();
	private EntityManagerFactory emf;
	private String name = "ApplicationEntityManager";
	public final static JpaUtil instance = new JpaUtil();

	public JpaUtil()
	{
		init();
	}

	public JpaUtil(EntityManagerFactory emf)
	{
		setEntityManagerFactory(emf);
	}

	private synchronized EntityManagerFactory createEntityManagerFactory()
	{
		try
		{
			ResourceBundle bundle = ResourceBundle.getBundle("META-INF/config");
			if (bundle.containsKey("persistenceUnit"))
			{
				name = bundle.getString("persistenceUnit");
			}
		}
		catch (Exception ex)
		{
			log.error(ex.getMessage());
		}
		try
		{
			emf = javax.persistence.Persistence.createEntityManagerFactory(name);
			return emf;
		}
		catch (Throwable ex)
		{
			log.error("Initial EntityManagerFactory creation failed. ", ex);
			throw new ExceptionInInitializerError(ex);
		}
	}

	protected synchronized void init()
	{
		if (emf == null || !emf.isOpen())
		{
			setEntityManagerFactory(createEntityManagerFactory());
		}
	}

	public synchronized EntityManagerFactory getEntityManagerFactory()
	{
		return emf;
	}

	public synchronized void setEntityManagerFactory(EntityManagerFactory emf)
	{
		this.emf = emf;
	}

	public synchronized EntityManager getCurrent()
	{
		EntityManager em = entityManagerPool.get();
		if (null == em || !em.isOpen())
		{
			em = emf.createEntityManager();
			log.debug("线程 [" + Thread.currentThread().getName() + "] 创建了一个会话" + em);
			entityManagerPool.set(em);
		}
		return em;
	}

	public synchronized void setCurrent(EntityManager entityManager)
	{
		EntityManager em = entityManagerPool.get();
		if (em == null)
		{
			;
		}
		else if (!em.isOpen())
		{
			;
		}
		else if (!em.equals(entityManager))
		{
			em.close();

		}
		entityManagerPool.set(entityManager);
	}

	public synchronized void close()
	{
		EntityManager em = entityManagerPool.get();
		if (null != em && em.isOpen())
		{
			entityManagerPool.set(null);
			em.close();
			log.debug("线程 [" + Thread.currentThread().getName() + "] 关闭了一个会话" + em);
		}
	}

	public java.sql.Connection getConnection()
	{
		getEntityManagerFactory();
		emf.createEntityManager().getTransaction().begin();
		java.sql.Connection connection = emf.createEntityManager().unwrap(java.sql.Connection.class);
		emf.createEntityManager().getTransaction().commit();
		return connection;
	}

	public void dispose()
	{
		close();
		if (emf != null)
		{
			emf.close();
		}
	}

}
